package cn.cellcom.agent.biz;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.online.wrapper.GroupWrapper;
import cn.cellcom.agent.pojo.TGroup;
import cn.cellcom.agent.pojo.TGroupUser;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TGroupForm;
import cn.cellcom.agent.util.RedisManager;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.reflect.ToString;
import cn.cellcom.jar.util.AU;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.IDGenerator;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MyException;

public class TGroupBiz extends AbstractBiz {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 这个是全局变量
	 */
	private static Map<String, GroupWrapper> groups = new HashMap<String, GroupWrapper>();

	@Override
	public List delete(HttpServletRequest req, ActionForm form, Object obj) {

		return null;
	}

	@Override
	public Object add(HttpServletRequest req, ActionForm form, Object obj) throws MyException {
		TGroupForm fm = (TGroupForm) form;
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		try {
			log.info("add log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getNo();
			// 你必须修改这里的id值
			if (key != null
					&& this.getDao().myGet("from " + TGroup.class.getSimpleName() + " where no=? and pid=?",
							new String[] { key, user.getPid() }) != null) {
				return "该服务号已经存在，不要重复添加";
			}
			TGroup pojo = new TGroup();
			// 以下为pojo的必填字段
			CopyUtil.copy(req, pojo, null, false);
			pojo.setOrg(user.getOrg());
			pojo.setPid(user.getPid());
			pojo.setId("GRP_" + IDGenerator.getDefaultUUID());
			this.getDao().mySave(pojo);

			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "新增数据出现错误", e);
		}
	}

	@Override
	public Object modify(HttpServletRequest req, ActionForm form, Object obj) throws MyException {
		TGroupForm fm = (TGroupForm) form;
		LogonSession ls = new LogonSession(req);
		try {
			log.info("modify log：" + ls.getAttribute("attribute.id") + "[" + req.getRemoteAddr() + "]");
			log.info(ToString.toString(fm, false));
		} catch (MyException e) {
		}
		try {
			java.lang.String key = fm.getId();
			TGroup pojo = (TGroup) this.getDao().myGet(TGroup.class, key);
			if (pojo == null) {
				return "修改的记录不存在";
			}
			log.info("被修改的pojo：" + ToString.toString(TGroup.class, pojo, false));
			// 以下为pojo的必填字段
			CopyUtil.copy(req, pojo, null, false);
			this.getDao().myUpdate(pojo);
			//修改过就删除redis的数据,等待下次需要再重新载入redis
			RedisManager.getInstance().getGroupInfo().remove(pojo.getId());
			return pojo;
		} catch (MyException e) {
			return LogUtil.e(this.getClass(), "修改数据出现错误", e);
		}

	}

	/**
	 * 查询某个技能组下的坐席
	 * 
	 * @param org
	 * @param groupId
	 * @return
	 */
	public List<TGroupUser> getAgents(String pid, String groupId) throws MyException {
		String hql = "from " + TGroupUser.class.getSimpleName() + " where pid=? and groupId=?";
		String[] values = new String[] { pid, groupId };
		return this.getDao().myList(hql, values);
	}

	/**
	 * 将坐席绑定到技能组
	 * 
	 * @param groupId
	 * @param users
	 * @return
	 */
	public Object bindAgents(String org, String pid, String groupId, String[] users) throws MyException {
		// 删除已有的绑定关系
		List list = getAgents(pid, groupId);
		this.getDao().myDelete(list);
		for (int i = 0; users != null && i < users.length; i++) {
			TGroupUser gu = new TGroupUser();
			gu.setGroupId(groupId);
			gu.setId(IDGenerator.getDefaultUUID());
			gu.setOrg(org);
			gu.setPid(pid);
			gu.setUser(users[i]);
			gu.setSwitchPolicy(1);// TODO
			this.getDao().mySave(gu);
		}
		return Env.SUCCESS;
	}

	/**
	 * 获取技能组
	 * 
	 * @param groupId
	 * @return
	 * @throws MyException
	 */
	public GroupWrapper loadGroupToMemory(String groupId) throws MyException {
		GroupWrapper group = groups.get(groupId);
		if (group == null) {
			TGroup group0 = (TGroup) this.getDao().myGet(TGroup.class, groupId);
			group = new GroupWrapper(group0);
			groups.put(groupId, group);
			log.info("[{}] group in memory is null, so get from db and load it into memory", groupId);
		} else {
			log.info("[{}] group got in memory", groupId);
		}
		return group;
	}

	/**
	 * 获取技能组
	 * 
	 * @param channel
	 * @param channel
	 * 
	 * @param groupId
	 * @return
	 * @throws MyException
	 */
	public List<TGroup> getGroupList(String pid) throws MyException {
		String hql = "from " + TGroup.class.getSimpleName() + " where pid=?";
		return this.getDao().myList(hql, new String[] { pid });
	}

	/**
	 * 获取某些组下面的成员
	 * 
	 * @param groups2
	 * @return
	 * @throws MyException
	 */
	public List getGroupsAndMembers(String pid, List<TGroup> groups2) throws MyException {
		if (AU.isBlank(groups2)) {
			return AU.getNewList(null);
		}

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < groups2.size(); i++) {
			sb.append("'").append(groups2.get(i).getId()).append("',");
		}
		String sb2 = sb.substring(0, sb.length() - 1);

		String hql = "select a, c from " + TGroup.class.getSimpleName() + " as a, " + TGroupUser.class.getSimpleName() + " as b, "
				+ TUser.class.getSimpleName() + " as c where a.id=b.groupId and b.user=c.id and a.pid=? and a.id in (" + sb2 + ")";
		String[] values = new String[] { pid };
		return this.getDao().myList(hql, values);

	}

	/**
	 * 获取某个技能组
	 * 
	 * @param groupId
	 * @return
	 * @throws MyException
	 */
	public TGroup getGroup(String groupId) throws MyException {
		if(StringUtils.isBlank(groupId)) {
			return null;
		}
		TGroup group = RedisManager.getInstance().getGroupInfo().getObject(groupId, TGroup.class);
		if (group == null) {
			group = (TGroup) this.getDao().myGet(TGroup.class, groupId);
			RedisManager.getInstance().getGroupInfo().putObject(group.getId(), group);
		}
		return group;
	}
}
